<template>
    <div>
        <Header></Header>
        <div class="m-substance">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="ruleForm.title"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input type="textarea" v-model="ruleForm.description"></el-input>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <mavon-editor
                            v-model="ruleForm.content"
                            :placeholder="'开始创作，开始你的表演···'"
                            :toolbars="toolbars"
                            :toolbarsBackground="'#FFC1C1'"
                            @change="change"
                            @imgAdd="imgAdd"
                            @imgDel="imgDel"
                            ref="md"
                            style="height: 70vh">
                    </mavon-editor>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
                    <el-button @click="resetForm('ruleForm')">取消</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
    import Header from "../components/Header"

    export default {
        name: "BlogEdit",
        components: {Header},
        data() {
            return {
                ruleForm: {
                    id: '',
                    title: '',
                    description: '',
                    content: '',
                    html: ''
                },
                rules: {
                    title: [
                        {required: true, message: '请输入标题', trigger: 'blur'},
                        {min: 3, max: 25, message: '长度在 3 到 25 个字符', trigger: 'blur'}
                    ],
                    description: [
                        {required: true, message: '请输入描述', trigger: 'blur'}
                    ],
                    content: [
                        {required: true, message: '请输入内容', trigger: 'blur'}
                    ],
                },
                //参数
                toolbars: {
                    bold: true, // 粗体
                    italic: true, // 斜体
                    header: true, // 标题
                    underline: true, // 下划线
                    strikethrough: true, // 中划线
                    mark: true, // 标记
                    superscript: true, // 上角标
                    subscript: true, // 下角标
                    quote: true, // 引用
                    ol: true, // 有序列表
                    ul: true, // 无序列表
                    link: true, // 链接
                    imagelink: true, // 图片链接
                    code: true, // code
                    table: true, // 表格
                    fullscreen: true, // 全屏编辑
                    readmodel: true, // 沉浸式阅读
                    htmlcode: true, // 展示html源码
                    help: true, // 帮助
                    /* 1.3.5 */
                    undo: true, // 上一步
                    redo: true, // 下一步
                    trash: true, // 清空
                    save: true, // 保存（触发events中的save事件）
                    /* 1.4.2 */
                    navigation: true, // 导航目录
                    /* 2.1.8 */
                    alignleft: true, // 左对齐
                    aligncenter: true, // 居中
                    alignright: true, // 右对齐
                    /* 2.2.1 */
                    subfield: true, // 单双栏模式
                    preview: true, // 预览
                }
            };
        },
        methods: {
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        const _this = this
                        this.$axios.post("/blog/edit", this.ruleForm, {
                            headers: {
                                "Authorization": localStorage.getItem("token")
                            }
                        }).then(res => {
                            console.log(res.data.data)
                            _this.$alert('操作成功！', '提示', {
                                confirmButtonText: '确定',
                                callback: action => {
                                    _this.$router.push("/blogs")
                                }
                            });
                        })
                    } else {
                        console.log('error!');
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            // 图片文件添加回调事件(filename: 写在md中的文件名, File: File Object)
            imgAdd(pos, $file) {
                let param = new FormData()
                param.append("file", $file)
                // 缓存图片信息
                // this.img_file[pos] = $file
                this.$axios({
                    url: "/file/uploadImg",
                    method: "post",
                    data: param,
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        "token": localStorage.getItem("token")
                    }
                }).then(res => {
                    // console.log(res)
                    // console.log(res.data.data)
                    if (res.data.data === 0) {
                        alert("图片上传失败")
                        return
                    }
                    let url = "http://localhost:8081" + res.data.data
                    this.$refs.md.$img2Url(pos, url)
                })
            },
            // 图片文件删除回调事件(filename: 写在md中的文件名)
            imgDel(pos) {
                // 删除缓存的图片信息
                // delete this.img_file[pos]
            },
            // 编辑区发生变化的回调事件(render: value 经过markdown解析后的结果)
            change(value, render) {
                this.html = render
            }
        },
        created() {
            const blogId = this.$route.params.blogId
            console.log(blogId)
            const _this = this
            if (blogId) {
                this.$axios.get("/blog/detail/" + blogId).then(res => {
                    console.log(res)
                    const blog = res.data.data
                    _this.ruleForm.id = blog.id
                    _this.ruleForm.title = blog.title
                    _this.ruleForm.description = blog.description
                    _this.ruleForm.content = blog.content
                })
            }
        }
    }
</script>

<style scoped>
    .m-substance {
        text-align: center;
    }
</style>